import urllib.request
import os
import platform
import subprocess

def download_npcap():
    try:
        npcap_url = "https://npcap.com/dist/npcap-1.81.exe"
        file_name = "npcap-1.81.exe"
        print("Downloading Npcap...", end='')
        urllib.request.urlretrieve(npcap_url, file_name)
        print("Done.")
    except Exception as e:
        print(f"Npcap 下载失败: {e}")

def download_winpcap():
    try:
        winpcap_url = "https://www.winpcap.org/install/bin/WinPcap_4_1_3.exe"
        file_name = "WinPcap_4_1_3.exe"
        print("Downloading WinPcap...", end='')
        urllib.request.urlretrieve(winpcap_url, file_name)
        print("Done.")
    except Exception as e:
        print(f"WinPcap 下载失败: {e}")

def install_libpcap_on_linux():
    try:
        distro = platform.system().lower()
        if distro == 'linux':
            if 'ubuntu' in platform.platform().lower() or 'debian' in platform.platform().lower():
                print("Downloading libpcap... ",end='')
                subprocess.run(['sudo', 'apt-get', 'update'], check=True)
                subprocess.run(['sudo', 'apt-get', 'install', '-y', 'libpcap-dev'], check=True)
                print("Done.")
            elif 'centos' in platform.platform().lower() or 'rhel' in platform.platform().lower():
                print("Downloading libpcap... ",end='')
                subprocess.run(['sudo', 'yum', 'install', '-y', 'libpcap-devel'], check=True)
                print("Done.")
            else:
                print("未知的 Linux 发行版，请手动使用包管理器安装 libpcap。")
        else:
            print("不是 Linux 系统，无法执行 Linux 安装操作。")
    except subprocess.CalledProcessError as e:
        print(f"libpcap 安装失败: {e}")
    except Exception:
        print("无法确定 Linux 发行版，请手动使用包管理器安装 libpcap。")

if __name__ == "__main__":
    if os.name == 'nt':
        download_npcap()
        download_winpcap()
    elif os.name == 'posix':
        install_libpcap_on_linux()
    else:
        print("不支持的操作系统。")